//
//  RegisteredVC.m
//  JingzhiForBusiness
//
//  Created by Admin on 2017/6/1.
//  Copyright © 2017年 cuixiaocun. All rights reserved.
//

#import "RegisteredVC.h"
#import "TPKeyboardAvoidingScrollView.h"
#import "MOFSPickerManager.h"

@interface RegisteredVC ()<UITextFieldDelegate,SRActionSheetDelegate,CXCNavgationDelegate>
{
    //底部scrollview
    TPKeyboardAvoidingScrollView *bgScrollView;
    NSString *levelString;
    NSString *memberlat;
    NSString *memberlng;
    NSString *photoString;
    NSInteger listTime;
    NSTimer *huoquTimer;
    UIButton *sendCodeBtn;
    //下一步按钮
    UIButton*nextBtn;
    UIImageView *imgV;

}
@end

@implementation RegisteredVC

- (void)viewDidLoad {
    
    [super viewDidLoad];
    NavgationView *nav =[[NavgationView alloc]initWithFrame:CGRectMake(0, 0, CXCWidth, 64) with:@"会员登录" isBackBtn:@"YES" rightBtnName:@"NO"];
    [self.view addSubview:nav];
    nav.delegate =self;
    nav.navLabel.text =@"会员注册";
    self.view.backgroundColor =BGColor;
    [self mainView];
}
- (void)retunButtonAction
{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)mainView
{
    bgScrollView =[[TPKeyboardAvoidingScrollView alloc] initWithFrame:CGRectMake(0, 64,CXCWidth, CXCHeight-64 )];
    [bgScrollView setUserInteractionEnabled:YES];
    [bgScrollView setBackgroundColor:BGColor];
    [self.view addSubview:bgScrollView];
    [bgScrollView setContentSize:CGSizeMake(CXCWidth, 1610*Width)];
    NSArray*leftArr =@[@"推荐人",@"账号",@"密码",@"确认密码",@"昵称",@"手机号",@"微信号",@"QQ",@"公司名称",@"公司负责人",@"营业执照",@"",@"",@"",] ;
    NSArray *rightArr =@[@"推荐人账号",@"账号",@"6-16位数字、字母或字符",@"确认密码",@"昵称",@"手机号",@"微信号",@"QQ",@"公司名称",@"公司负责人",@"营业执照",@"",@""];
    //列表
    for (int i=0; i<11; i++) {
        UIView *bgview =[[UIView alloc]init];
        bgview.backgroundColor =[UIColor whiteColor];
        [bgScrollView addSubview:bgview];
        
        UILabel* labe = [[UILabel alloc]initWithFrame:CGRectMake(32*Width, 0,200*Width , 106*Width)];
        labe.text = leftArr[i];
        labe.font = [UIFont systemFontOfSize:15];
        labe.textColor = [UIColor grayColor];
        [bgview addSubview:labe];
        if (i!=10&&i!=11) {
        UITextField *inputText = [[UITextField alloc] init];
        [inputText setTag:i+10];
        if (i==2||i==3) {
            inputText.secureTextEntry =YES;

        }else if(i==5)
        {
            [inputText setKeyboardType:UIKeyboardTypePhonePad];
        }
        [inputText setPlaceholder:rightArr[i]];
        [inputText setDelegate:self];
        inputText.textAlignment=NSTextAlignmentRight;

        [inputText setFont:[UIFont systemFontOfSize:16]];
        [inputText setTextColor:[UIColor blackColor]];
        [inputText setFrame:CGRectMake(300*Width, 0,420*Width,106*Width)];
//        [inputText setClearButtonMode:UITextFieldViewModeWhileEditing];
        [bgview addSubview:inputText];
            if (i==11) {
//                {
//                    inputText.frame =CGRectMake(290*Width, 0*Width,250*Width,106*Width);
//                    UIButton *butto = [[UIButton alloc]initWithFrame:CGRectMake(520*Width, 13*Width, 200*Width, 80*Width)];
//                    [butto.titleLabel setFont:[UIFont systemFontOfSize:14]];
//                    [butto setTitle:@"获取验证码" forState:UIControlStateNormal];
//                    [butto setTitle:[NSString stringWithFormat:@"%lds",listTime] forState:UIControlStateSelected];
//                    butto.tag = 345;
//                    butto.backgroundColor =BGColor;
//                    [butto setTitleColor:NavColor forState:UIControlStateNormal];
//                    [butto setTitleColor:[UIColor colorWithRed:180/255.0 green:180/255.0 blue:180/255.0 alpha:1] forState:UIControlStateSelected];
//                    [butto addTarget:self action:@selector(yanzhengma:) forControlEvents:UIControlEventTouchUpInside];
//                    [bgview addSubview:butto];
//                    
//                    
//                }
            }
        }else
        {
            //代理级别、选择地区、上传身份证
            UIButton *chooseBtn =[[UIButton alloc]initWithFrame:CGRectMake(290*Width, 0,580*Width,106*Width)];
            [bgview addSubview:chooseBtn];
            chooseBtn.tag =10+i;
            [chooseBtn addTarget:self action:@selector(levelChoosen:) forControlEvents:UIControlEventTouchUpInside];
            //文字
            UILabel* wzlabe = [[UILabel alloc]initWithFrame:CGRectMake(0*Width, 0,380*Width , 106*Width)];
            wzlabe.text = rightArr[i];
            wzlabe.tag =20+i;
            wzlabe.textAlignment=NSTextAlignmentRight;
            wzlabe.font = [UIFont systemFontOfSize:16];
            wzlabe.textColor = TextGrayGrayColor;
            [chooseBtn addSubview:wzlabe];
            //箭头
            UIImageView  *jiantou =[[UIImageView alloc]initWithFrame:CGRectMake(680*Width, 35*Width,30*Width , 30*Width)];
            [bgview addSubview:jiantou];
            [jiantou setImage:[UIImage imageNamed:@"register_btn_nextPage"]];
        
        
        }
        //横线
        UIImageView*xian =[[UIImageView alloc]init];
        xian.backgroundColor =BGColor;
        [bgview addSubview:xian];
        xian.frame =CGRectMake(0,104*Width, CXCWidth, 2*Width);

        if (i==0) {
            bgview.frame =CGRectMake(0, 20*Width, CXCWidth, 106*Width);
            
        }else if(i<4&&i>0)
        {
            bgview.frame =CGRectMake(0, 40*Width+i*106*Width, CXCWidth, 106*Width);
        }else if (i>=4&&i<8)
        {
            bgview.frame =CGRectMake(0, 60*Width+i*106*Width, CXCWidth, 106*Width);
        }else
        {
            bgview.frame =CGRectMake(0, 80*Width+i*106*Width, CXCWidth, 106*Width);
        }
    }
    
    imgV=[[UIImageView alloc]initWithFrame:CGRectMake(140*Width,1358*Width+0*Width , 470*Width, 600*Width)];
    imgV.backgroundColor =[UIColor redColor];
    [imgV setImage:[UIImage imageNamed:@""]];
    [bgScrollView addSubview:imgV];
    imgV.hidden =YES;
    
    

    
    //下一步按钮
    nextBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [nextBtn setFrame:CGRectMake(40*Width,1358*Width , 670*Width, 88*Width)];
    [nextBtn setBackgroundColor:NavColor];
    [nextBtn.layer setCornerRadius:4];
    [nextBtn.layer setMasksToBounds:YES];
    [nextBtn setTitle:@"注册" forState:UIControlStateNormal];
    [nextBtn.titleLabel setTextColor:[UIColor whiteColor]];
    [nextBtn.titleLabel setFont:[UIFont boldSystemFontOfSize:18]];
    [nextBtn addTarget:self action:@selector(nextStep) forControlEvents:UIControlEventTouchUpInside];
    [bgScrollView addSubview:nextBtn];
    

    
    

}
- (void)photoUpLoadToFWQ
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"html/text",@"text/json", @"text/html", @"text/plain",nil];
    NSString *url=[NSString stringWithFormat:@"%@/%@",SERVERURL,@"index.php/Home/Login/upidcard"];
    
    [manager POST:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        NSData *imageData = UIImageJPEGRepresentation(imgV.image, 0.1);
        //使用日期生成图片名称
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyyMMddHHmmss";
        NSString *fileName = [NSString stringWithFormat:@"%@.png",[formatter stringFromDate:[NSDate date]]];
        [formData appendPartWithFileData :imageData name : @"upimg" fileName : fileName mimeType : @"image/jpg/png/jpeg" ];
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:self.view];
        
        NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"图片请求成功JSON:%@", JSON);
        if ([ [NSString stringWithFormat:@"%@",[JSON objectForKey:@"code"]]isEqualToString:@"0"])
        {
            NSString *addressStr =[NSString stringWithFormat:@"%@",[[JSON objectForKey:@"data"] objectForKey:@"url"]];
            
            [self  registToFWQ:addressStr];
            
        }else
        {
            [ProgressHUD dismiss];
            [MBProgressHUD showError:[NSString stringWithFormat:@"%@",[JSON objectForKey:@"msg"]] ToView:self.view];
        }
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [MBProgressHUD hideHUDForView:self.view];
        [MBProgressHUD showError:@"加载出错" ToView:self.view];
        NSLog(@"请求失败:%@", error.description);
    }];
    


}
- (void)nextStep
{
    
    
    [self photoUpLoadToFWQ];
    
}

-(void)registToFWQ:(NSString *)upLoadPhoneStr
{
    //判断
    for (int i = 0; i<12; i++) {
        //收起所有键盘
        UITextField *inputTExt = (UITextField *)[self.view viewWithTag:i+10];
        [inputTExt resignFirstResponder];
        if (i!=10&&i!=11) {
            //不为空
            if([inputTExt.text isEqualToString:@""])
            {
                [MBProgressHUD showError:@"信息不完整" ToView:self.view];
                return;
            }
        }
        if (i==5) {
            //判断手机号
            if (![PublicMethod isMobileNumber:inputTExt.text ]) {
                [MBProgressHUD showError:@"手机号码输入错误" ToView:self.view];
                return;
            }
        }else if(i==9)
        {
        }else if (i==4)
        {
        }
    }
    
    UITextField *topAngetNumTF = (UITextField *)[self.view viewWithTag:10];
    
    UITextField *accountTF = (UITextField *)[self.view viewWithTag:11];
    UITextField *inputTExtMM = (UITextField *)[self.view viewWithTag:12];
    UITextField *inputTExtQRMM = (UITextField *)[self.view viewWithTag:13];
    UITextField *nameTF = (UITextField *)[self.view viewWithTag:14];
    UITextField *phoneTF = (UITextField *)[self.view viewWithTag:15];
    UITextField *wxTF = (UITextField *)[self.view viewWithTag:16];
    UITextField *qqTF = (UITextField *)[self.view viewWithTag:17];
    
    UITextField *compNameTF = (UITextField *)[self.view viewWithTag:18];
    UITextField *comPeopleTF = (UITextField *)[self.view viewWithTag:19];
    
    //判断密码是否一致
    if (![inputTExtMM.text isEqualToString:inputTExtQRMM.text]) {
        [MBProgressHUD showError:@"两次密码不一致" ToView:self.view];
        return;
    }
    
    NSMutableDictionary *dic1 = [NSMutableDictionary dictionary];
    [dic1 setDictionary:@{
                          @"parentAccount":[NSString stringWithFormat:@"%@",topAngetNumTF.text],
                          @"account":[NSString stringWithFormat:@"%@",accountTF.text],
                          @"password":[NSString stringWithFormat:@"%@",inputTExtMM.text],
                          @"password2":[NSString stringWithFormat:@"%@",inputTExtQRMM.text],
                          @"name":[NSString stringWithFormat:@"%@",nameTF.text],
                          @"phone":[NSString stringWithFormat:@"%@",phoneTF.text],
                          @"wechat":[NSString stringWithFormat:@"%@",wxTF.text],
                          @"qq":[NSString stringWithFormat:@"%@",qqTF.text  ],
                          @"company":[NSString stringWithFormat:@"%@",compNameTF.text],
                          @"companyAdmin":[NSString stringWithFormat:@"%@",comPeopleTF.text],
                          @"upimg":upLoadPhoneStr
                          }];
    NSLog(@"%@",dic1);
    
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"html/text",@"text/json", @"text/html", @"text/plain",nil];
    NSString *url=[NSString stringWithFormat:@"%@/%@",SERVERURL,@"index.php/Home/Login/regMember"];
    //    NSDictionary *dic = [PublicMethod ASCIIwithDic:dic1];//当加密的时候用
    NSMutableDictionary*parameter =[NSMutableDictionary dictionary];
    int num = (arc4random() % 10000);
    NSString*  randomNumber = [NSString stringWithFormat:@"%.4d", num];
    NSLog(@"%@", randomNumber);
    
    [parameter setDictionary:dic1];
    [manager POST:url parameters:parameter constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
//        NSData *imageData = UIImageJPEGRepresentation(imgV.image, 0.1);
//        //使用日期生成图片名称
//        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
//        formatter.dateFormat = @"yyyyMMddHHmmss";
//        NSString *fileName = [NSString stringWithFormat:@"%@.png",[formatter stringFromDate:[NSDate date]]];
//        [formData appendPartWithFileData :imageData name : @"upimg" fileName : fileName mimeType : @"image/jpg/png/jpeg" ];
//        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:self.view];
        
        NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"图片请求成功JSON:%@", JSON);
        if ([ [NSString stringWithFormat:@"%@",[JSON objectForKey:@"code"]]isEqualToString:@"0"])
        {
            
        }else
        {
            [ProgressHUD dismiss];
            [MBProgressHUD showError:[NSString stringWithFormat:@"%@",[JSON objectForKey:@"msg"]] ToView:self.view];
        }
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [MBProgressHUD hideHUDForView:self.view];
        [MBProgressHUD showError:@"加载出错" ToView:self.view];
        NSLog(@"请求失败:%@", error.description);
    }];

}
    
    
    
    
    
    

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    //点击其他地方收起键盘
    for (int i = 0; i<12; i++) {
        UITextField *inputTExt = (UITextField *)[self.view viewWithTag:i+10];
        [inputTExt resignFirstResponder];
    }


}
- (void)levelChoosen:(UIButton *)btn
{
    //收起键盘
    for (int i = 0; i<12; i++) {
        UITextField *inputTExt = (UITextField *)[self.view viewWithTag:i+10];
        [inputTExt resignFirstResponder];
    }
    if (btn.tag==17) {
        //选择代理
        SRActionSheet *actionSheet = [SRActionSheet sr_actionSheetViewWithTitle:@"请选择代理级别"
                                                                    cancelTitle:@"取消"
                                                               destructiveTitle:nil
                                                                     withNumber:@"7" withLineNumber:@"1"
                                                                    otherTitles:@[@"一级代理",@"二级代理",@"三级代理",@"四级代理",@"五级代理",@"六级代理"]
                                                                    otherImages:nil
                                                              selectActionBlock:^(SRActionSheet *actionSheet, NSInteger index) {
                                                                  
                                                                  if (index<0||index>5) {
                                                                      return;
                                                                  }
                                                                  [self actionSheetButtonAtIndex:index];
                                                                  
                                                                  
                                                                  NSLog(@"%zd", index);
                                                              }];
        actionSheet.number=@"7";
        actionSheet.lineNumber=@"1";
        

        [actionSheet show];
        
        
        
        
        
    }else if (btn.tag==20){
        
        [self photoUpLoad];
    }else if (btn.tag==18)
    {
    
    }







}
-(void) actionSheetButtonAtIndex:(NSInteger)buttonIndex
{
    UILabel *labelOne  =[self.view viewWithTag:27];
    labelOne.textColor =[UIColor blackColor];
    levelString =[NSString stringWithFormat:@"%ld",buttonIndex];

    switch (buttonIndex) {
        case 0:
            
            labelOne.text =@"一级代理";
            break;
        case 1:
            labelOne.text =@"二级代理";

            break;
        case 2:
            labelOne.text =@"三级代理";

            break;
        case 3:
            labelOne.text =@"四级代理";

            break;
        case 4:
            labelOne.text =@"五级代理";

            break;
        case 5:
            labelOne.text =@"六级代理";

            break;
        case 6:
            labelOne.textColor =TextGrayGrayColor;
            labelOne.text =@"选择级别";

            break;
   
        default:
            break;
    }

}
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSInteger existedLength = textField.text.length;
    NSInteger selectedLength = range.length;
    NSInteger replaceLength = string.length;
    if (textField.tag==15) {
        if (existedLength - selectedLength + replaceLength >= 12) {
            
            [textField resignFirstResponder];
            return NO;
            
        }

    }else if (textField.tag==19)
    {
        if (existedLength - selectedLength + replaceLength >= 19) {
            
            [textField resignFirstResponder];
            return NO;
           
        }
    }else if (textField.tag==12)
    {
        
        if (existedLength - selectedLength + replaceLength >= 17) {
            [MBProgressHUD showError:@"密码为6-16位" ToView:self.view];
            
            [textField resignFirstResponder];
            return NO;
            
        }
        
        
    }

    return YES;
    


}
- (void)successUpPhoto:(NSString *)str
{

    UILabel *labelOne  =[self.view viewWithTag:30];
    labelOne.textColor =NavColor;
    labelOne.text =@"已上传";
    photoString =str;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}
- (void)getInfoLLL
{
    UITextField *accountLabel =[self.view viewWithTag:13];
    
    NSMutableDictionary *dic1 = [NSMutableDictionary dictionary];
    [dic1 setDictionary:@{
                          @"account":accountLabel.text,
                          @"type":@"3"
                          }];
    
    [PublicMethod AFNetworkPOSTurl:@"Home/Login/getnum" paraments:dic1  addView:self.view success:^(id responseDic) {
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseDic options:NSJSONReadingMutableContainers error:nil];
        if ([ [NSString stringWithFormat:@"%@",[dict objectForKey:@"code"]]isEqualToString:@"0"]) {
            UIButton *sender = (UIButton *)[self.view  viewWithTag:345];
            [MBProgressHUD showSuccess:@"验证码正在发送中" ToView:self.view];
            sender.selected=!sender.selected;
            [huoquTimer invalidate];
            listTime =60;
            huoquTimer =[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(daoshu) userInfo:nil repeats:YES];
            [huoquTimer fire];
            [sender setUserInteractionEnabled:NO];
            
        }else
        {
            UIButton *sender = (UIButton *)[self.view  viewWithTag:345];
            [sender setUserInteractionEnabled:YES];
            
        }
        
    } fail:^(NSError *error) {
        UIButton *sender = (UIButton *)[self.view  viewWithTag:345];
        [sender setUserInteractionEnabled:YES];
    }];
    
    
    
}
- (void)yanzhengma:(UIButton *)sender
{
    if (sender.selected) {
        sender.userInteractionEnabled =YES;
        
        
        return;
    }else{
        
        sender.userInteractionEnabled =NO;
        
        
    }
    [UIView animateWithDuration:0.3 animations:^{
        
        self.view.transform =CGAffineTransformIdentity;
        
    }];
    
    [self getInfoLLL];
    
    
    
}
-(void)daoshu
{
    listTime-=1;
    UIButton *yanzhengBtn = (UIButton *)[self.view viewWithTag:345];
    
    if (listTime==0) {
        [yanzhengBtn setSelected:NO];
        [huoquTimer invalidate];
        listTime =60;
        [yanzhengBtn setUserInteractionEnabled:YES];
        
    }else{
        [yanzhengBtn setTitle:[NSString stringWithFormat:@"%lds",listTime] forState:UIControlStateSelected];
        
    }
}

-(void)sendCodeBtnPressed
{
    if (huoquTimer) {
        [huoquTimer fire];
    }else{
        huoquTimer =[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(waitCode) userInfo:nil repeats:YES];
        [huoquTimer fire];
    }
}
-(void)waitCode
{
    [self getInfoLLL];
    
    if (listTime>1) {
        listTime--;
        [sendCodeBtn setTitle:[NSString stringWithFormat:@"%lds",listTime] forState:UIControlStateNormal];
        [sendCodeBtn setTitleColor:[UIColor colorWithWhite:189/255.0 alpha:1] forState:UIControlStateNormal];
        
        [sendCodeBtn setUserInteractionEnabled:NO];
    }else{
        listTime=60;
        [sendCodeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
        [sendCodeBtn setTitleColor:[UIColor colorWithRed:201/255.0 green:33/255.0 blue:44/255.0 alpha:1] forState:UIControlStateNormal];
        [sendCodeBtn setUserInteractionEnabled:YES];
        [huoquTimer invalidate];
        
    }
}
- (void)photoUpLoad
{
    if (IOS7)
    {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"获取图片" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        //判断是否支持相机，模拟器没有相机
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
        {
            UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action)
                                            {
                                                //相机
                                                UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
                                                imagePickerController.delegate = self;
                                                imagePickerController.allowsEditing = YES;
                                                imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
                                                [self presentViewController:imagePickerController animated:YES completion:^{}];
                                            }];
            [alertController addAction:defaultAction];
        }
        UIAlertAction *defaultAction1 = [UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            //相册
            UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
            imagePickerController.delegate = self;
            imagePickerController.allowsEditing = YES;
            imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            [self presentViewController:imagePickerController animated:YES completion:^{
                imagePickerController.delegate = self;
            }];
        }];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action)
                                       {
                                       }];
        
        [alertController addAction:cancelAction];
        [alertController addAction:defaultAction1];
        //弹出试图，使用UIViewController的方法
        [self presentViewController:alertController animated:YES completion:nil];
    }
    else
    {
        UIActionSheet *sheet;
        //判断是否支持相机，模拟器没有相机
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
        {
            sheet = [[UIActionSheet alloc] initWithTitle:@"获取图片" delegate:self cancelButtonTitle:nil destructiveButtonTitle:@"取消" otherButtonTitles:@"拍照",@"从相册选择", nil];
        }
        else
        {
            sheet = [[UIActionSheet alloc] initWithTitle:@"获取图片" delegate:self cancelButtonTitle:nil destructiveButtonTitle:@"取消" otherButtonTitles:@"从相册选择", nil];
        }
        [sheet showInView:self.view];
    }
    
}
-(void) actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSInteger sourctType = 0;
    //判断是否支持相机
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        switch (buttonIndex) {
            case 1:
                sourctType = UIImagePickerControllerSourceTypeCamera;
                break;
            case 2:
                sourctType = UIImagePickerControllerSourceTypePhotoLibrary;
                break;
            default:
                break;
        }
    }
    else
    {
        if (buttonIndex == 1)
        {
            sourctType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
        }
    }
    //跳转到相机或者相册页面
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.delegate = self;
    imagePickerController.allowsEditing = YES;
    imagePickerController.sourceType = sourctType;
    [self presentViewController:imagePickerController animated:YES completion:nil];
    
    
}
//IOS7以上的都要调用方法，选择完成后调用该方法
- (void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    [picker dismissViewControllerAnimated:YES completion:^{}];
    UIImage *image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
    // 把头像图片存到本地
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"Img.png"]];// 保存文件的名称
    NSData *imageData = UIImageJPEGRepresentation(image, 0.1);
    [imageData writeToFile:filePath atomically:YES];
    
    UIImage *img =[[UIImage alloc] initWithContentsOfFile:filePath];
    UIImage *savedImage =[self image:img rotation:(img.imageOrientation) ] ;
    
    imgV.image=savedImage;
    imgV.hidden =NO;
    [nextBtn setFrame:CGRectMake(40*Width,1358*Width+600*Width+100*Width , 670*Width, 88*Width)];
    [bgScrollView setContentSize:CGSizeMake(CXCWidth, 1610*Width+600*Width)];

    
}
- (UIImage *)image:(UIImage *)image rotation:(UIImageOrientation)orientation
{
    
    long double rotate = 0.0;
    CGRect rect;
    float translateX = 0;
    float translateY = 0;
    float scaleX = 1.0;
    float scaleY = 1.0;
    
    switch (orientation) {
        case UIImageOrientationLeft:
            rotate = M_PI_2;
            rect = CGRectMake(0, 0, image.size.height, image.size.width);
            translateX = 0;
            translateY = -rect.size.width;
            scaleY = rect.size.width/rect.size.height;
            scaleX = rect.size.height/rect.size.width;
            break;
        case UIImageOrientationRight:
            rotate = 3 * M_PI_2;
            rect = CGRectMake(0, 0, image.size.height, image.size.width);
            translateX = -rect.size.height;
            translateY = 0;
            scaleY = rect.size.width/rect.size.height;
            scaleX = rect.size.height/rect.size.width;
            break;
        case UIImageOrientationDown:
            rotate = M_PI;
            rect = CGRectMake(0, 0, image.size.width, image.size.height);
            translateX = -rect.size.width;
            translateY = -rect.size.height;
            break;
        default:
            rotate = 0.0;
            rect = CGRectMake(0, 0, image.size.width, image.size.height);
            translateX = 0;
            translateY = 0;
            break;
    }
    
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    //做CTM变换
    CGContextTranslateCTM(context, 0.0, rect.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);
    CGContextRotateCTM(context, rotate);
    CGContextTranslateCTM(context, translateX, translateY);
    
    CGContextScaleCTM(context, scaleX, scaleY);
    //绘制图片
    CGContextDrawImage(context, CGRectMake(0, 0, rect.size.width, rect.size.height), image.CGImage);
    
    UIImage *newPic = UIGraphicsGetImageFromCurrentImageContext();
    
    return newPic;
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
